package cachaframework;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 缓存重建线程
 */
public class RebuildCacheThread implements Runnable {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run() {
        RebuildCacheQueue rebuildCacheQueue = RebuildCacheQueue.getInstance();

        while (true) {
            ProductInfo productInfo = rebuildCacheQueue.takeProductInfo();

            ProductInfo existedProductInfo = getProductInfoFromReidsCache(productInfo.getId());

            if (existedProductInfo != null) {
                // 比较当前数据的时间版本比已有数据的时间版本是新还是旧
                try {
                    Date date = sdf.parse(productInfo.getModifiedTime());
                    Date existedDate = sdf.parse(existedProductInfo.getModifiedTime());

                    if (date.before(existedDate)) {
                        System.out.println("current date[" + productInfo.getModifiedTime() + "] is before existed date[" + existedProductInfo.getModifiedTime() + "]");
                        continue;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("current date[" + productInfo.getModifiedTime() + "] is after existed date[" + existedProductInfo.getModifiedTime() + "]");
            } else {
                System.out.println("existed product info is null......");
            }
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            LockSupport.unpark(productInfo.getThread());

        }
    }

    private ProductInfo getProductInfoFromReidsCache(Long id) {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setId(123L);
        productInfo.setName("123name");
        productInfo.setPrice(1234D);
        productInfo.setPictureList("PictureList");
        productInfo.setSpecification("Specification");
        productInfo.setService("Service");
        productInfo.setColor("Color");
        productInfo.setSize("size");
        productInfo.setShopId(22222L);
        productInfo.setModifiedTime("2021-09-20");
        return productInfo;
    }

}
